/**   
* @{#} MatchBy.java Create on 2013-6-26 下午12:32:35   
*   
* Copyright (c) 2012 by Baidu.   
*/
package objtable.algm;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.google.common.base.Charsets;
import com.google.common.io.Files;

import objtable.core.ScriptEnv;
import objtable.core.TableCenter;
import objtable.struct.Row;

/**   
* @author <a href="mailto:zhangbo07@baidu.com">zhangbo07</a>  
* @version 1.0   
*/

public class JoinBy implements Algm3Row {
	private String condition;
	private String express;
	private boolean isAppend;

	/**
	 * @param simpleExpress 会用if语句进行包装
	 * @param complexExpress
	 * @param oneToOneCheck  是否是1对1映射的检查，如果不满足1对1映射的需求，则向外报错
	 */
	public JoinBy(String simpleExpress, String complexExpress, boolean append) {
		this.condition = simpleExpress;
		this.express = complexExpress;
		this.isAppend = append;
	}

	private String wrapExpress(String table) {
		String code = "";
		try {
			code = Files.toString(new File("./codescript/joinby.groovy"),
					Charsets.UTF_8);
		} catch (IOException e) {
			e.printStackTrace();
		}
		code = code.replaceAll("#1", condition);
		code = code.replaceAll("#2", "new " + table + "()");
		code = code.replaceAll("#3", express);
		return code;
	}

	public void execute(List<? extends Row> rowa, List<? extends Row> rowb,
			String tablename) {
		List<Row> rowc = new ArrayList<Row>();

		HashMap<String, Object> hm = ScriptEnv.cloneComputeObj();
		hm.put("a_objs", rowa);
		hm.put("b_objs", rowb);
		hm.put("c_objs", rowc);

		ScriptEnv.execute(wrapExpress(tablename), hm);

		if (isAppend && TableCenter.getTableData(tablename) != null) {
			TableCenter.getTableData(tablename).addAll(rowc);
		} else {
			TableCenter.putTableData(tablename, rowc);
		}
	}
}
